<template>
  <div class="import">
    <el-card>
      <h3>员工导入</h3>
      <el-alert
        type="warning"
        title="每次导入仅可添加1000名员工，姓名、手机、入职时间、聘用形式为必填项"
        show-icon
      ></el-alert>
      <myexcel :beforeUpload="beforeUpload" :onSuccess="onSuccess" class="myexcel"></myexcel>
    </el-card>
  </div>
</template>
<script>
import { addEmpListApi } from '@/api/employees'
export default {
  methods: {
    beforeUpload(file) {
      const less2m = file.size / 1024 / 1024 < 2
      if (!less2m) {
        this.$message.error('对不起,文件大小不能超过2M')
      }
      return less2m
    },
    async onSuccess(mydata) {
      // console.log(mydata)
      // 定义字典,中英文对应
      const mydir = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      // 将中文转化为英文属性
      const newAll = mydata.results.map(item => {
        var obj = {}
        Object.keys(item).forEach(key => {
          // key:入职日期 => mydire[key]:timeOfEntry
          // obj[mydir[key]]:obj.timeOfEntry  item[key]:item.入职日期
          if (key === '入职日期' || key === '转正日期') {
            obj[mydir[key]] = this.formatDate(item[key])
          } else {
            obj[mydir[key]] = item[key]
          }
        })
        return obj
      })
      await addEmpListApi(newAll)
      this.$router.push('/employees')
    },
    // 时间转换
    formatDate(days) {
      const timeStemp = (days - 1) * 24 * 60 * 60 * 1000
      const time = new Date(timeStemp)
      time.setFullYear(time.getFullYear() - 70)
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.import {
  margin: 20px;
  h3 {
    text-align: center;
  }
  .myexcel {
    margin-top: 100px;
  }
}
</style>
